package com.zy.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zy.dto.Result;
import com.zy.entity.Shop;
import com.zy.mapper.ShopMapper;
import com.zy.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zy.utils.CacheClient;
import com.zy.utils.SystemConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.util.*;

import static com.zy.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 张宇
 * @since 2024-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    //注入缓存工具类
    @Autowired
    private CacheClient cacheClient;

    /**
     * 根据id查询商铺信息
     *
     * @param id
     * @return
     */
    @Override
    public Result queryById(Long id) {
        //缓存穿透
        Shop shop = cacheClient.queryWithPassThrough(CACHE_SHOP_KEY, id, Shop.class,
                this::getById, Duration.ofMinutes(CACHE_SHOP_TTL));

        //互斥锁解决缓存击穿
        //Shop shop = queryWithMutex(id);

        //逻辑过期解决缓存击穿问题
//        Shop shop = cacheClient.queryWithLogicalExpire(CACHE_SHOP_KEY, id, Shop.class, this::getById, Duration.ofMinutes(30));
        if (shop == null) {
            return Result.fail("店铺不存在");
        }
        // 7.返回
        return Result.ok(shop);
    }


    /**
     * 互斥锁解决缓存击穿
     * @param id
     * @return
     */
    public Shop queryWithMutex(Long id){
        // 1.从redis查询商铺缓存
        String shopJson = redisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        // 2.判断是否存在,判断是不是有值
        if (StrUtil.isNotBlank(shopJson)) {
            // 3.存在,直接返回
            Shop shop = JSON.parseObject(shopJson, Shop.class);
            return shop;
        }
        //判断是不是null,这时候是空字符串(两种情况,null和空字符串)
        if(shopJson != null){
            return null;
        }
        // 4.实现缓存重建
        // 4.1获取互斥锁,每一个店铺有他们自己的锁
        Shop shop = null;
        try {
            boolean flag = tryLock(LOCK_SHOP_KEY + id);
            // 4.2判断是否获取成功,false的话加!为真,执行下面逻辑
            if (!flag) {
                // 4.3获取失败,休眠一段时间
                Thread.sleep(50);
                // 4.2.2重试,递归
                return queryWithMutex(id);
            }
            // 4.4获取成功,根据id查询数据库
            shop = getById(id);
            // 模拟重建需要的时间
            Thread.sleep(200);
            // 5.不存在,返回404
            if (shop == null) {
                // 将null值写入缓存
                redisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, "", Duration.ofMinutes(CACHE_NULL_TTL));
                return null;
            }
            // 6.存在,写入redis
            redisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSON.toJSONString(shop), Duration.ofMinutes(CACHE_SHOP_TTL));

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 7.释放互斥锁
            unLock(LOCK_SHOP_KEY + id);
        }
        // 8.返回
        return shop;
    }


    /**
     * 尝试获取锁
     * @param key
     * @return
     */
    private boolean tryLock(String key){
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(key, "1", Duration.ofSeconds(LOCK_SHOP_TTL));
        //Boolean为包装类型,需要拆箱,boolean为基本类型,拆箱可能出现空指针
        return BooleanUtil.isTrue(flag);
    }

    /**
     * 释放锁
     * @param key
     */
    private void unLock(String key){
        redisTemplate.delete(key);
    }

    /**
     * 更新店铺信息
     *
     * @param shop
     * @return
     */
    @Override
    @Transactional
    public Result update(Shop shop) {
        Long id = shop.getId();
        if (id == null) {
            return Result.fail("店铺id不能为空");
        }
        // 1.更新数据库
        updateById(shop);
        // 2.删除缓存
        redisTemplate.delete(CACHE_SHOP_KEY + shop.getId());
        return null;
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        if(x == null || y == null){
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
        }
        // 计算分页参数
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;//起始行
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;//结束行
        // 按照距离排序, GEOSERCH BYLONLAT  x y BYRADIUS 10 WITHDISTANCE ASC COUNT 10
        String key = SHOP_GEO_KEY + typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = redisTemplate.opsForGeo().search(key, GeoReference.fromCoordinate(x, y), new Distance(5000),
                RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end));
        // 解析出id
        if(results == null){
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        if(list.size() <= from){
            return Result.ok(Collections.emptyList());
        }
        List<Long> ids = new ArrayList(list.size());
        Map<String, Distance> distanceMap = new HashMap<>(list.size());
        // 截取 from 到 end , 逻辑分页
        list.stream().skip(from).forEach(result -> {
            String shopIdStr = result.getContent().getName();
            // 商户id
            ids.add(Long.valueOf(shopIdStr));
            Distance distance = result.getDistance();
            // 商户id + 距离
            distanceMap.put(shopIdStr, distance);
        });
        String idStr = StrUtil.join(",", ids);
        List<Shop> shopList =query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();
        shopList.forEach(shop->{
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        });
        return Result.ok(shopList);

    }


}
